package at.fhj.itm11.fotorater.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;

import javax.inject.Inject;

import org.apache.commons.lang3.RandomStringUtils;


import net.coobird.thumbnailator.Thumbnails;

public class PhotoUploader {
	
	@Inject
	private Logger log;
	

	private final File UPLOAD_DIR = new File(DeploymentUtils.getDeploymentPath() + "/resources/photos");
	
	public String uploadAndCreateThumbnail(byte[] fileContent, String fileType) throws IOException {

		File f;
		String fileName;
		do {
			fileName = RandomStringUtils.randomAlphanumeric(8);
			f = new File(UPLOAD_DIR, fileName + "." + fileType);
		} while(f.exists());

		OutputStream fOut = new BufferedOutputStream(new FileOutputStream(f.toString()));
		
		fOut.write(fileContent);
		
		fOut.flush();
		fOut.close();
		
		Thumbnails.of(f).size(200, 200).outputFormat(fileType).toFile(new File(UPLOAD_DIR, "t_" + fileName + "." + fileType));

		return fileName + "." + fileType;
	}
}
